const Notice = require("../model/notice.model");
const Record = require("../model/record.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;

const { createRecord } = require("../service/record.service");
class NoticeService {
  /**
   * 更新公告浏览记录
   * @param record_id 记录id
   * @param type view:浏览 like:点赞
   * @returns {Promise<boolean>}
   */
  async updateNoticeRecord(record_id,type) {
    const res = await Record.update(
      { view: seq.literal(`${type} + 1`) },
      {
        where: {
          id: record_id
        },
      }
    );
    return res[0] > 0;
  }
  /**
   * 创建
   * @returns {Promise<{code: string, message: string}>}
   * @param notice
   */
  async createNotice(notice) {
    const { id } = await createRecord();
    const res = await Notice.create({ ...notice, record_id: id });
    return res.dataValues;
  }

  /**
   * 更新
   * @param id
   * @param notice
   * @returns {Promise<boolean>}
   */
  async updateNotice(id, notice) {
    const res = await Notice.update(notice, { where: { id } });
    return res[0] > 0;
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<boolean>}
   */

  async removeNotice(id) {
    const res = await Notice.destroy({ where: { id } });
    return res > 0;
  }

  /**
   * 恢复
   * @param id
   * @returns {Promise<boolean>}
   */

  async restoreNotice(id) {
    const res = await Notice.restore({ where: { id } });
    return res > 0;
  }

  async findNotice({ pageNum, pageSize, notice_title }) {
    const offset = (pageNum - 1) * pageSize;
    const whereOpt1 = {};

    notice_title &&
      Object.assign(whereOpt1, {
        notice_title: {
          [Op.like]: `%${notice_title}%`,
        },
      });
    const { count, rows } = await Notice.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      where: whereOpt1,
      include: [
        {
          model: Record,
          as: "record_info",
        },
      ],
      order: [["createdAt", "DESC"]],
    });

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  async findNoticeInfo(id) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });

    const res = await Notice.findOne({
      where: whereOpt,
      include: [
        {
          model: Record,
          as: "record_info",
        },
      ],
    });

    return res ? res.dataValues : null;
  }
}

module.exports = new NoticeService();
